package com.hsurosy.domain.strategy.service.rule.tree.impl;

import com.hsurosy.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.hsurosy.domain.strategy.repository.IStrategyRepository;
import com.hsurosy.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.hsurosy.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author Hsu琛君珩
 * @Date 2024-10-19 15:25
 * @Description 次数锁节点逻辑处理类
 * @Version: v1.0.0
 */
@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyRepository strategyRepository; // 策略数据仓储

    /**
     * 执行规则树的次数锁逻辑处理
     *
     * @param userId 用户ID
     * @param strategyId 抽奖策略ID
     * @param awardId 奖品ID
     * @param ruleValue 规则值，表示限制的抽奖次数
     * @param endDateTime 活动结束时间
     * @return TreeActionEntity 包含规则的检查结果和后续的操作类型（放行或接管）
     */
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-次数锁 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);

        // 1. 定义规则中的抽奖次数限制值
        long raffleCount = 0L;
        try {
            // 2. 解析规则值中的次数限制
            raffleCount = Long.parseLong(ruleValue);
        } catch (Exception e) {
            // 如果规则中的次数配置不正确，抛出异常
            throw new RuntimeException("规则过滤-次数锁异常 ruleValue: " + ruleValue + " 配置不正确");
        }

        // 查询用户抽奖次数 - 当天的。策略ID:活动ID 1:1 的配置，可以直接用 strategyId 查询
        Integer userRaffleCount = strategyRepository.queryTodayUserRaffleCount(userId, strategyId);

        // 3. 如果用户的抽奖次数大于等于规则限定值，规则放行
        if (userRaffleCount >= raffleCount) {
            log.info("规则过滤-次数锁【放行】 userId: {} strategyId: {} awardId: {} raffleCount: {} userRaffleCount: {}", userId, strategyId, awardId, userRaffleCount, userRaffleCount);
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW) // 放行
                    .build();
        }

        log.info("规则过滤-次数锁【拦截】 userId: {} strategyId: {} awardId: {} raffleCount: {} userRaffleCount: {}", userId, strategyId, awardId, userRaffleCount, userRaffleCount);

        // 4. 如果用户的抽奖次数小于规则限定值，规则拦截，接管流程
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER) // 接管
                .build();
    }

}
